<template>
	<el-dialog
		:title="editData ? '编辑车辆' : '新增车辆'"
		v-model="dialogVisible"
		width="80%"
		:destroy-on-close="true"
		@close="handleClose"
	>
		<el-form
			ref="formRef"
			:model="formData"
			:rules="rules"
			label-width="140px"
			class="pr-8"
		>
			<!-- 基础信息 -->
			<div class="mb-4">
				<div class="text-base font-bold mb-4">基础信息</div>
				<el-row :gutter="20">
					<el-col :span="8">
						<el-form-item label="车牌号" prop="hphm">
							<el-input v-model="formData.hphm" />
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="车辆类型" prop="vehicleType">
							<el-select v-model="formData.vehicleType" class="w-full">
								<el-option
									v-for="dict in vehicle_type"
									:key="dict.value"
									:label="dict.label"
									:value="dict.value"
								/>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="能源类型" prop="energyType">
							<el-select v-model="formData.energyType" class="w-full">
								<el-option
									v-for="dict in energy_type"
									:key="dict.value"
									:label="dict.label"
									:value="dict.value"
								/>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="8">
						<el-form-item label="所属车队" prop="fleetId">
							<el-select
								v-model="formData.fleetId"
								class="w-full"
								@change="handleFleetChange"
							>
								<el-option
									v-for="item in fleetOptions"
									:key="item.id"
									:label="item.fleetName"
									:value="item.id"
								/>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="车主" prop="ownerName">
							<el-input v-model="formData.ownerName" />
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="车主电话" prop="ownerPhone">
							<el-input v-model="formData.ownerPhone" />
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="8">
						<el-form-item label="经营类型" prop="businessType">
							<el-select v-model="formData.businessType" class="w-full">
								<el-option
									v-for="dict in business_type"
									:key="dict.value"
									:label="dict.label"
									:value="dict.value"
								/>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="核定载质量" prop="approvedLoad">
							<el-input v-model="formData.approvedLoad">
								<template #append>kg</template>
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="总质量" prop="totalMass">
							<el-input v-model="formData.totalMass">
								<template #append>kg</template>
							</el-input>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="8">
						<el-form-item label="检定高度" prop="approvedHeight">
							<el-input v-model="formData.approvedHeight">
								<template #append>m</template>
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="检定宽度" prop="approvedWidth">
							<el-input v-model="formData.approvedWidth">
								<template #append>m</template>
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="检定长度" prop="approvedLength">
							<el-input v-model="formData.approvedLength">
								<template #append>m</template>
							</el-input>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="8">
						<el-form-item label="车架号" prop="frameNumber">
							<el-input v-model="formData.frameNumber" />
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="发动机编号" prop="engineNumber">
							<el-input v-model="formData.engineNumber" />
						</el-form-item>
					</el-col>
				</el-row>
			</div>

			<!-- 证照信息 -->
			<div class="mb-4">
				<div class="text-base font-bold mb-4">证照信息</div>
				<el-row :gutter="20">
					<el-col :span="8">
						<el-form-item label="行驶证编号" prop="travelCertNo">
							<el-input v-model="formData.travelCertNo" />
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="行驶证失效日期" prop="travelCertExpiry">
							<el-date-picker
								v-model="formData.travelCertExpiry"
								type="date"
								class="w-full"
								value-format="YYYY-MM-DD"
							/>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="8">
						<el-form-item label="道路运输许可证号" prop="transportCertNo">
							<el-input v-model="formData.transportCertNo" />
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="运输证失效日期" prop="transportCertExpiry">
							<el-date-picker
								v-model="formData.transportCertExpiry"
								type="date"
								class="w-full"
								value-format="YYYY-MM-DD"
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</div>

			<!-- 车检信息 -->
			<div class="mb-4">
				<div class="text-base font-bold mb-4">车检信息</div>
				<el-row :gutter="20">
					<el-col :span="8">
						<el-form-item
							label="交强险生效日期"
							prop="trafficInsuranceEffective"
						>
							<el-date-picker
								v-model="formData.trafficInsuranceEffective"
								type="date"
								class="w-full"
								value-format="YYYY-MM-DD"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="交强险失效日期" prop="trafficInsuranceExpiry">
							<el-date-picker
								v-model="formData.trafficInsuranceExpiry"
								type="date"
								class="w-full"
								value-format="YYYY-MM-DD"
							/>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="8">
						<el-form-item
							label="商业险生效日期"
							prop="commercialInsuranceEffective"
						>
							<el-date-picker
								v-model="formData.commercialInsuranceEffective"
								type="date"
								class="w-full"
								value-format="YYYY-MM-DD"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item
							label="商业险失效日期"
							prop="commercialInsuranceExpiry"
						>
							<el-date-picker
								v-model="formData.commercialInsuranceExpiry"
								type="date"
								class="w-full"
								value-format="YYYY-MM-DD"
							/>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="8">
						<el-form-item
							label="超赔险生效日期"
							prop="overCompensationEffective"
						>
							<el-date-picker
								v-model="formData.overCompensationEffective"
								type="date"
								class="w-full"
								value-format="YYYY-MM-DD"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="超赔险失效日期" prop="overCompensationExpiry">
							<el-date-picker
								v-model="formData.overCompensationExpiry"
								type="date"
								class="w-full"
								value-format="YYYY-MM-DD"
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</div>

			<!-- 挂车信息 -->
			<div class="mb-4">
				<div class="text-base font-bold mb-4">挂车信息（选填）</div>
				<el-row :gutter="20">
					<el-col :span="8">
						<el-form-item label="行驶证编号" prop="trailerTravelCertNo">
							<el-input v-model="formData.trailerTravelCertNo" />
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="行驶证失效日期" prop="trailerTravelCertExpiry">
							<el-date-picker
								v-model="formData.trailerTravelCertExpiry"
								type="date"
								class="w-full"
								value-format="YYYY-MM-DD"
							/>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="8">
						<el-form-item
							label="道路运输许可证号"
							prop="trailerTransportCertNo"
						>
							<el-input v-model="formData.trailerTransportCertNo" />
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item
							label="运输证失效日期"
							prop="trailerTransportCertExpiry"
						>
							<el-date-picker
								v-model="formData.trailerTransportCertExpiry"
								type="date"
								class="w-full"
								value-format="YYYY-MM-DD"
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</div>

			<!-- 附件信息 -->
			<div>
				<div class="text-base font-bold mb-4">附件信息</div>
				<el-row :gutter="20">
					<el-col :span="8">
						<el-form-item label="车辆正面" prop="vehicleFrontImage" required>
							<ImageUpload
								v-model="formData.vehicleFrontImage"
								uploadUrl="/admin/sys-file/upload"
								:auto-upload="true"
								tip="车辆正面照片，支持jpg/png格式"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="行驶证" prop="travelCertImage" required>
							<ImageUpload
								v-model="formData.travelCertImage"
								uploadUrl="/admin/sys-file/upload"
								:auto-upload="true"
								tip="行驶证照片，支持jpg/png格式"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item
							label="道路运输许可证"
							prop="transportCertImage"
							required
						>
							<ImageUpload
								v-model="formData.transportCertImage"
								uploadUrl="/admin/sys-file/upload"
								:auto-upload="true"
								tip="道路运输许可证照片，支持jpg/png格式"
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</div>
		</el-form>

		<template #footer>
			<span class="dialog-footer">
				<el-button @click="handleClose">取消</el-button>
				<el-button type="primary" @click="handleSubmit" :loading="loading">
					确定
				</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue';
import ImageUpload from '/@/components/ImageUpload.vue';
import { ElMessage } from 'element-plus';
import {
	addVehicle,
	updateVehicle,
	getVehicleById,
} from '/@/api/tscompany/vehicle';
import { getFleetList } from '/@/api/tscompany/fleet'; // 假设有这个API
import { useDict } from '/@/hooks/dict';

const props = defineProps({
	modelValue: {
		type: Boolean,
		default: false,
	},
	editData: {
		type: Object,
		default: () => null,
	},
});

const emit = defineEmits(['update:modelValue', 'success']);

// 获取字典数据
const { vehicle_type } = useDict(['vehicle_type']);
const { energy_type } = useDict(['energy_type']);
const { business_type } = useDict(['business_type']);

const dialogVisible = ref(false);
const loading = ref(false);
const formRef = ref();
const fleetOptions = ref([]);

// 表单数据
const formData = reactive({
	fleetId: null, // 车队id
	fleetName: '', // 车队名称
	hphm: '', // 车牌号
	vehicleType: '', // 车辆类型(0:小型货车，1:中型货车，2:大型货车)
	energyType: '', // 能源类型(0:燃油车，1:新能源车)
	ownerName: '', // 车主姓名
	ownerPhone: '', // 车主联系电话
	businessType: '', // 经营类型(0:自营，1:联合经营)
	approvedLoad: '', // 核定载质量(kg)
	totalMass: '', // 总质量(kg)
	approvedHeight: '', // 核定高度(m)
	approvedWidth: '', // 核定宽度(m)
	approvedLength: '', // 核定长度(m)
	frameNumber: '', // 车架号
	engineNumber: '', // 发动机编号
	travelCertNo: '', // 行驶证编号
	travelCertExpiry: '', // 行驶证失效日期
	transportCertNo: '', // 道路运输许可证号
	transportCertExpiry: '', // 运输证失效日期
	trafficInsuranceEffective: '', // 交强险生效日期
	trafficInsuranceExpiry: '', // 交强险失效日期
	commercialInsuranceEffective: '', // 商业险生效日期
	commercialInsuranceExpiry: '', // 商业险失效日期
	overCompensationEffective: '', // 超赔险生效日期
	overCompensationExpiry: '', // 超赔险失效日期
	trailerTravelCertNo: '', // 挂车行驶证编号
	trailerTravelCertExpiry: '', // 挂车行驶证失效日期
	trailerTransportCertNo: '', // 挂车运输证编号
	trailerTransportCertExpiry: '', // 挂车运输证失效日期
	vehicleFrontImage: '', // 车辆正面照片
	travelCertImage: '', // 行驶证照片
	transportCertImage: '', // 道路运输许可证照片
});

// 表单校验规则
const rules = reactive({
	hphm: [{ required: true, message: '请输入车牌号', trigger: 'blur' }],
	vehicleType: [
		{ required: true, message: '请选择车辆类型', trigger: 'change' },
	],
	energyType: [
		{ required: true, message: '请选择能源类型', trigger: 'change' },
	],
	fleetId: [{ required: true, message: '请选择所属车队', trigger: 'change' }],
	ownerName: [{ required: true, message: '请输入车主', trigger: 'blur' }],
	ownerPhone: [{ required: true, message: '请输入车主电话', trigger: 'blur' }],
	businessType: [
		{ required: true, message: '请选择经营类型', trigger: 'change' },
	],
	approvedLoad: [
		{ required: true, message: '请输入核定载质量', trigger: 'blur' },
		{
			type: 'number',
			message: '核定载质量必须为数字',
			trigger: 'blur',
			transform: (value) => Number(value),
		},
	],
	totalMass: [
		{ required: true, message: '请输入总质量', trigger: 'blur' },
		{
			type: 'number',
			message: '总质量必须为数字',
			trigger: 'blur',
			transform: (value) => Number(value),
		},
	],
	approvedHeight: [
		{
			type: 'number',
			message: '检定高度必须为数字',
			trigger: 'blur',
			transform: (value) => (value ? Number(value) : undefined),
		},
	],
	approvedWidth: [
		{
			type: 'number',
			message: '检定宽度必须为数字',
			trigger: 'blur',
			transform: (value) => (value ? Number(value) : undefined),
		},
	],
	approvedLength: [
		{
			type: 'number',
			message: '检定长度必须为数字',
			trigger: 'blur',
			transform: (value) => (value ? Number(value) : undefined),
		},
	],
	travelCertNo: [
		{ required: true, message: '请输入行驶证编号', trigger: 'blur' },
	],
	transportCertNo: [
		{ required: true, message: '请输入道路运输许可证号', trigger: 'blur' },
	],
	vehicleFrontImage: [
		{ required: true, message: '请上传车辆正面照片', trigger: 'change' },
	],
	travelCertImage: [
		{ required: true, message: '请上传行驶证照片', trigger: 'change' },
	],
	transportCertImage: [
		{ required: true, message: '请上传道路运输许可证照片', trigger: 'change' },
	],
});

// 获取车队列表
const fetchFleetList = async () => {
	try {
		const res = await getFleetList();
		if (res && (res.code === 200 || res.code == 0)) {
			fleetOptions.value = res.data || [];
		}
	} catch (error) {
		console.error('获取车队列表失败', error);
	}
};

// 处理车队选择变化
const handleFleetChange = (value) => {
	const selectedFleet = fleetOptions.value.find((item) => item.id === value);
	if (selectedFleet) {
		formData.fleetName = selectedFleet.name;
	}
};

// 监听弹窗显示状态
watch(
	() => props.modelValue,
	async (val) => {
		dialogVisible.value = val;
		if (val) {
			// 获取车队列表
			await fetchFleetList();

			if (props.editData) {
				// 编辑时填充表单数据
				if (props.editData.id) {
					// 如果有ID，通过API获取最新的详细数据
					loading.value = true;
					try {
						const res = await getVehicleById(props.editData.id);
						if (res && res.code === 200) {
							Object.assign(formData, res.data);
						} else {
							ElMessage.error(res.msg || '获取车辆详情失败');
						}
					} catch (error) {
						console.error('获取车辆详情出错', error);
						ElMessage.error('获取车辆详情失败');
					} finally {
						loading.value = false;
					}
				} else {
					// 直接使用传入的数据
					Object.assign(formData, props.editData);
				}
			}
		}
	},
);

// 监听弹窗关闭
watch(dialogVisible, (val) => {
	emit('update:modelValue', val);
	if (!val) {
		// 重置表单
		formRef.value?.resetFields();
		Object.keys(formData).forEach((key) => {
			formData[key] = '';
		});
		formData.fleetId = null;
	}
});

// 初始化
onMounted(() => {
	fetchFleetList();
});

// 提交表单
const handleSubmit = async () => {
	if (!formRef.value) return;
	await formRef.value.validate(async (valid) => {
		if (valid) {
			loading.value = true;
			try {
				const submitData = { ...formData };

				// 处理数字字段
				const numberFields = [
					'approvedLoad',
					'totalMass',
					'approvedHeight',
					'approvedWidth',
					'approvedLength',
				];
				numberFields.forEach((field) => {
					if (
						submitData[field] !== '' &&
						submitData[field] !== null &&
						submitData[field] !== undefined
					) {
						submitData[field] = Number(submitData[field]);
					}
				});

				// 如果是编辑模式，需要添加ID
				if (props.editData && props.editData.id) {
					submitData.id = props.editData.id;
				}

				// 根据是否有ID判断是新增还是更新
				const api =
					props.editData && props.editData.id ? updateVehicle : addVehicle;
				const res = await api(submitData);

				if (res && res.code === 200) {
					ElMessage.success(
						props.editData && props.editData.id
							? '更新车辆成功'
							: '新增车辆成功',
					);
					emit('success', res.data);
					handleClose();
				} else {
					ElMessage.error(res.msg || '操作失败');
				}
			} catch (error) {
				console.error('提交表单出错', error);
				ElMessage.error('操作失败，请重试');
			} finally {
				loading.value = false;
			}
		}
	});
};

// 关闭弹窗
const handleClose = () => {
	dialogVisible.value = false;
};
</script>

<style scoped>
:deep(.el-form-item) {
	margin-bottom: 22px;
}

:deep(.el-form-item__label) {
	padding-bottom: 8px;
}

:deep(.el-row) {
	margin-bottom: 8px;
}
</style>
